﻿using Microsoft.EntityFrameworkCore;
using YDT_PaymentService.Domain.Entities;
using YDT_PaymentService.Domain.Enums;
using YDT_PaymentService.Domain.Interfaces;
using YDT_PaymentService.Infrastructure.Data;

namespace YDT_PaymentService.Infrastructure.Repositories
{
    /// <summary>
    /// 支付仓储实现 - 实现支付数据访问
    /// </summary>
    public class PaymentRepository : IPaymentRepository
    {
        private readonly PaymentDbContext _context;

        /// <summary>
        /// 构造函数
        /// </summary>
        public PaymentRepository(PaymentDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 根据ID获取支付记录
        /// </summary>
        public async Task<Payment?> GetByIdAsync(Guid id)
        {
            return await _context.Payments
                .FirstOrDefaultAsync(p => p.Id == id);
        }

        /// <summary>
        /// 根据支付单号获取支付记录
        /// </summary>
        public async Task<Payment?> GetByPaymentCodeAsync(string paymentCode)
        {
            return await _context.Payments
                .FirstOrDefaultAsync(p => p.PaymentCode == paymentCode);
        }

        /// <summary>
        /// 根据订单ID获取支付记录
        /// </summary>
        public async Task<Payment?> GetByOrderIdAsync(Guid orderId)
        {
            return await _context.Payments
                .FirstOrDefaultAsync(p => p.OrderId == orderId);
        }

        /// <summary>
        /// 获取用户的所有支付记录
        /// </summary>
        public async Task<IEnumerable<Payment>> GetByUserIdAsync(Guid userId)
        {
            return await _context.Payments
                .Where(p => p.UserId == userId)
                .OrderByDescending(p => p.CreateTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 根据状态获取支付记录
        /// </summary>
        public async Task<IEnumerable<Payment>> GetByStatusAsync(PaymentStatus status)
        {
            return await _context.Payments
                .Where(p => p.PaymentStatus == status)
                .OrderByDescending(p => p.CreateTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 获取所有支付记录
        /// </summary>
        public async Task<IEnumerable<Payment>> GetAllAsync()
        {
            return await _context.Payments
                .OrderByDescending(p => p.CreateTime)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();
        }

        /// <summary>
        /// 分页获取支付记录
        /// </summary>
        public async Task<(IEnumerable<Payment> Payments, int TotalCount)> GetPagedAsync(int pageIndex, int pageSize)
        {
            var query = _context.Payments
                .OrderByDescending(p => p.CreateTime);

            var totalCount = await query.CountAsync();
            var payments = await query
                .Skip((pageIndex - 1) * pageSize)
                .Take(pageSize)
                .AsNoTracking() // 只读查询，不跟踪变更
                .ToListAsync();

            return (payments, totalCount);
        }

        /// <summary>
        /// 添加支付记录
        /// </summary>
        public async Task AddAsync(Payment payment)
        {
            await _context.Payments.AddAsync(payment);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 更新支付记录
        /// </summary>
        public async Task UpdateAsync(Payment payment)
        {
            _context.Payments.Update(payment);
            await _context.SaveChangesAsync();
        }

        /// <summary>
        /// 删除支付记录
        /// </summary>
        public async Task DeleteAsync(Guid id)
        {
            var payment = await _context.Payments.FindAsync(id);
            if (payment != null)
            {
                _context.Payments.Remove(payment);
                await _context.SaveChangesAsync();
            }
        }

        /// <summary>
        /// 检查支付记录是否存在
        /// </summary>
        public async Task<bool> ExistsAsync(Guid id)
        {
            return await _context.Payments.AnyAsync(p => p.Id == id);
        }

        /// <summary>
        /// 检查支付单号是否存在
        /// </summary>
        public async Task<bool> PaymentCodeExistsAsync(string paymentCode)
        {
            return await _context.Payments.AnyAsync(p => p.PaymentCode == paymentCode);
        }
    }
}
